package com.wwy.consumer;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.rabbitmq.client.Channel;
import com.wwy.mapper.TbOrderMapper;
import com.wwy.module.TbOrder;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author 王伟羽
 * @date 2024/3/13 17:49
 */

@Component
public class PublishConsumerTwo {

    @Resource
    private TbOrderMapper tbOrderMapper;

//    @RabbitListener(queues = "publish_queue_one")
//    public void publishOne(String message) {
//        System.out.println("队列1收到的消息" + message);
//        TbOrder tbOrder = JSONObject.parseObject(message, TbOrder.class);
//        if(Objects.nonNull(tbOrder)){
//            //先查询看是否已经入库
//            List<TbOrder> tbOrders = tbOrderMapper.selectList(tbOrder);
//            if(CollectionUtils.isEmpty(tbOrders)){
//                tbOrder.setId(IdUtil.objectId());
//                tbOrderMapper.insert(tbOrder);
//            }
//        }
//    }


    @RabbitListener(queues = "publish_queue_two")
    public void publishTwo(String message) {
        System.out.println("队列2收到的消息" + message);
    }

    @RabbitListener(queues = "publish_queue_one")
    public void publishOne(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 处理消息逻辑...
            byte[] payload = message.getBody();
            // 如果负载是文本，并且你知道编码，你可以将其转换为字符串
            String text = new String(payload, "UTF-8");
            System.out.println("text = " + text);
            TbOrder tbOrder = JSONObject.parseObject(text, TbOrder.class);
            if(Objects.nonNull(tbOrder)){
                //先查询看是否已经入库
                List<TbOrder> tbOrders = tbOrderMapper.selectList(tbOrder);
                if(CollectionUtils.isEmpty(tbOrders)){
                    tbOrder.setId(IdUtil.objectId());
                    tbOrderMapper.insert(tbOrder);
                    // 手动发送确认消息
                    channel.basicAck(deliveryTag, false);
                    System.out.println(tbOrder.getOrderId()+"消费成功！");
                }
            }
        } catch (Exception e) {
            // 处理异常逻辑...
            System.out.println("消息消费失败！");
            // 如果需要，可以发送拒绝消息并重新入队
             channel.basicReject(deliveryTag, true);
        }
    }
}
